package com.eorchis.module.preauthorizationregistration.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.eorchis.core.basedao.dao.IDaoSupport;
import com.eorchis.core.basedao.entity.IBaseEntity;
import com.eorchis.core.service.impl.AbstractBaseService;
import com.eorchis.module.classdept.service.IClassDeptService;
import com.eorchis.module.classdept.ui.commond.ClassDeptQueryCommond;
import com.eorchis.module.classdept.ui.commond.ClassDeptValidCommond;
import com.eorchis.module.classuser.dao.IClassUserDao;
import com.eorchis.module.classuser.ui.commond.ClassUserQueryCommond;
import com.eorchis.module.deptassignedinfo.dao.IDeptAssignedInfoDao;
import com.eorchis.module.deptassignedinfo.domain.DeptAssignedInfo;
import com.eorchis.module.deptassignedinfo.service.IDeptAssignedInfoService;
import com.eorchis.module.deptassignedinfo.ui.commond.DeptAssignedInfoQueryCommond;
import com.eorchis.module.deptassignedinfo.ui.commond.DeptAssignedInfoValidCommond;
import com.eorchis.module.exceluitls.domain.excel.ExcelCell;
import com.eorchis.module.exceluitls.domain.excel.ExcelRow;
import com.eorchis.module.exceluitls.domain.excel.ExcelSheet;
import com.eorchis.module.interioruser.domain.DeptSignupBean;
import com.eorchis.module.interioruser.domain.UserInfoBean;
import com.eorchis.module.interioruser.service.IInteriorUserService;
import com.eorchis.module.interioruser.ui.commond.InteriorUserQueryCommond;
import com.eorchis.module.preauthorizationregistration.dao.IPreAuthorizationRegistrationDao;
import com.eorchis.module.preauthorizationregistration.domain.PreAuhorzaionQueryBean;
import com.eorchis.module.preauthorizationregistration.domain.PreAuthorizationRegistration;
import com.eorchis.module.preauthorizationregistration.domain.PreSqSyUserBean;
import com.eorchis.module.preauthorizationregistration.service.IPreAuthorizationRegistrationService;
import com.eorchis.module.preauthorizationregistration.ui.commond.PreAuthorizationRegistrationQueryCommond;
import com.eorchis.module.preauthorizationregistration.ui.commond.PreAuthorizationRegistrationValidCommond;
import com.eorchis.module.signupdept.domain.SignupDept;
import com.eorchis.module.trainingclass.domain.TrainingClass;
import com.eorchis.module.trainingclass.service.ITrainingClassService;
import com.eorchis.module.trainingclass.ui.commond.TrainingClassValidCommond;
import com.eorchis.module.user.domain.User;
import com.eorchis.utils.utils.PropertyUtil;

/**
 * Title: PreAuthorizationRegistrationServiceImpl<br>
 * Description: 个人报名预授权管理业务接口实现<br>
 * Company: GoldGov<br>
 * Copyright @ 2012 GoldGov .All rights reserved.<br>
 * @author Administrator
 * @createDate 2015-01-06
 * @version $Revision$
 */
// 声明本类为Server实现类，声明bean名称
@Service(value = "com.eorchis.module.preauthorizationregistration.service.impl.PreAuthorizationRegistrationServiceImpl")
public class PreAuthorizationRegistrationServiceImpl extends AbstractBaseService implements IPreAuthorizationRegistrationService {

	@Resource(name = "com.eorchis.module.preauthorizationregistration.dao.impl.PreAuthorizationRegistrationDaoImpl")
	private IPreAuthorizationRegistrationDao preAuthorizationRegistrationDao;
	// 单位年度参学名额表接口
	@Resource(name = "com.eorchis.module.deptassignedinfo.service.impl.DeptAssignedInfoServiceImpl")
	private IDeptAssignedInfoService deptAssignedInfoService;
	@Override
	public IDaoSupport getDaoSupport() {
		return preAuthorizationRegistrationDao;
	}
	
	@Resource(name = "com.eorchis.module.classuser.dao.impl.ClassUserDaoImpl")
	private IClassUserDao classUserDao;
	
	@Autowired
	@Qualifier("com.eorchis.module.trainingclass.service.impl.TrainingClassServiceImpl")
	private ITrainingClassService trainingClassService;
	
	@Resource(name = "com.eorchis.module.deptassignedinfo.dao.impl.DeptAssignedInfoDaoImpl")
	private IDeptAssignedInfoDao deptAssignedInfoDao;
	
	// 班级部门关系表接口
	@Autowired
	@Qualifier("com.eorchis.module.classdept.service.impl.ClassDeptServiceImpl")
	private IClassDeptService classDeptService;
	
	@Resource(name = "com.eorchis.module.interioruser.service.impl.InteriorUserServiceImpl")
	private IInteriorUserService interiorUserService;
	
	@Override
	@SuppressWarnings("unchecked")
	public PreAuthorizationRegistrationValidCommond toCommond(IBaseEntity entity) {
		return new PreAuthorizationRegistrationValidCommond((PreAuthorizationRegistration)entity);
	}
	private static Object o=new Object();
	/**
	 * 添加报名预授权
	 * @param String
	 * @return
	 * @throws Exception
	 * @author NingSS
	 * @date 2015-1-6
	 */
	@Override
	public String addPreAuthorizationRegistration(PreAuthorizationRegistrationValidCommond vCommond) throws Exception{
		String msg="";
		//调用dao层:根据部门id和登陆号查询此部门是否存在此用户
		List<UserInfoBean> users = preAuthorizationRegistrationDao.findBaseUser(vCommond.getLoginId(),vCommond.getDeptId());
		if(PropertyUtil.objectNotEmpty(users)&&users.size()>0){//存在
			Calendar a=Calendar.getInstance(); 
			//查询此用户在当前年是否已经报过预授权
			UserInfoBean userInfoBean=users.get(0);
			User user=new User();
			user.setUserId(userInfoBean.getUserId());
			PreAuthorizationRegistrationQueryCommond  queryCommond=new PreAuthorizationRegistrationQueryCommond();
			queryCommond.setSearchUserId(user.getUserId());
			queryCommond.setSearchYear(a.get(Calendar.YEAR));
			List<?> list=this.findAllList(queryCommond);
			if(PropertyUtil.objectNotEmpty(list)&&list.size()>0){//存在
				msg="不能重复添加用户！";
			}else{//不存在
				//查询此部门当前年普通班的参学名额
				DeptAssignedInfoQueryCommond quCommond=new DeptAssignedInfoQueryCommond();
				quCommond.setSearchYear(a.get(Calendar.YEAR));
				quCommond.setSearchDepId(vCommond.getDeptId());
				quCommond.setSearchClassType(DeptAssignedInfo.ORDINARY_CLASS);
				List<DeptAssignedInfoValidCommond> dlist=(List<DeptAssignedInfoValidCommond>) deptAssignedInfoService.findAllList(quCommond);
				//如果此部门当前年普通班的参学名额限报人数为0便不能添加，否则可以添加
				if(PropertyUtil.objectNotEmpty(dlist)&&dlist.size()>0){
					//获得此部门当前年普通班的参学名额限报人数
					int restrictPersonNum=dlist.get(0).getRestrictPersonNum();
					//查询此部门当前年的个人报名预授权人数
					int parNum=0;
					PreAuthorizationRegistrationQueryCommond  qCommond=new PreAuthorizationRegistrationQueryCommond();
					qCommond.setSearchYear(a.get(Calendar.YEAR));
					qCommond.setSearchDeptId(vCommond.getDeptId());
					List<?> preAuthorizationRegistrations=this.findAllList(qCommond);
					if(PropertyUtil.objectNotEmpty(preAuthorizationRegistrations)&&preAuthorizationRegistrations.size()>0){
						parNum=preAuthorizationRegistrations.size();
					}
					//如果个人报名预授权人数小于参学名额限报人数便可以添加，否则不能添加
					if(parNum<restrictPersonNum){
						//添加报名预授权
						PreAuthorizationRegistration preAuthorizationRegistration=new PreAuthorizationRegistration();
						preAuthorizationRegistration.setLoginId(vCommond.getLoginId());
						preAuthorizationRegistration.setYear(a.get(Calendar.YEAR));
						preAuthorizationRegistration.setUser(user);
						SignupDept department = new SignupDept();
						department.setDepid(vCommond.getDeptId());
						preAuthorizationRegistration.setDepartment(department);
						if(PropertyUtil.objectNotEmpty(vCommond.getUserName())){
							preAuthorizationRegistration.setUserName(vCommond.getUserName());
						}
						try{
							preAuthorizationRegistrationDao.save(preAuthorizationRegistration);
							msg="success";
						}catch(Exception e){
							e.printStackTrace();
						}
					}else{
						msg="单位年度报名预授权已满！";
					}
				}else{
					msg="此单位本年没有分配参学名额，请分配以后再添加报名预授权！";
				}
			}
		}else{//不存在
			msg="不存在此用户,请重新添加！";
		}
		return msg;
	}
	/**
	 * Excel导入报名预授权
	 * @param vCommond
	 * @param sheet
	 * @return
	 * @throws Exception
	 * @author NingSS
	 * @date 2015-1-6
	 */
	@Override
	public String importPreAuthorizationRegistration(PreAuthorizationRegistrationValidCommond vCommond,ExcelSheet sheet) throws Exception{
		synchronized(o) {
			List<PreAuthorizationRegistrationValidCommond> list=new ArrayList<PreAuthorizationRegistrationValidCommond>();
			StringBuffer rmsg=new StringBuffer();
			StringBuffer msg=new StringBuffer();
			List<ExcelRow> eRows=sheet.getRowList();
			if(PropertyUtil.objectNotEmpty(eRows)&&eRows.size()>1){
				Calendar a=Calendar.getInstance(); 
				//查询此部门当前年普通班的参学名额
				DeptAssignedInfoQueryCommond quCommond=new DeptAssignedInfoQueryCommond();
				quCommond.setSearchYear(a.get(Calendar.YEAR));
				quCommond.setSearchDepId(vCommond.getDeptId());
				quCommond.setSearchClassType(DeptAssignedInfo.ORDINARY_CLASS);
				List<DeptAssignedInfoValidCommond> dlist=(List<DeptAssignedInfoValidCommond>) deptAssignedInfoService.findAllList(quCommond);
				if(PropertyUtil.objectNotEmpty(dlist)&&dlist.size()>0){//存在参学名额
					//获得此部门当前年普通班的参学名额限报人数
					int restrictPersonNum=dlist.get(0).getRestrictPersonNum();
					//查询此部门当前年已经添加的预授权人数
					int parNum=0;
					PreAuthorizationRegistrationQueryCommond  qCommond=new PreAuthorizationRegistrationQueryCommond();
					qCommond.setSearchYear(a.get(Calendar.YEAR));
					qCommond.setSearchDeptId(vCommond.getDeptId());
					List<?> preAuthorizationRegistrations=this.findAllList(qCommond);
					if(PropertyUtil.objectNotEmpty(preAuthorizationRegistrations)&&preAuthorizationRegistrations.size()>0){
						parNum=preAuthorizationRegistrations.size();
					}
					//判断excel的表头对不对
					boolean state=false;
					try {
						ExcelRow topRow=eRows.get(0);
						List<ExcelCell> topRowCells =topRow.getCellList();
						if(topRowCells.size()>2) {
							state=true;
						}
						if(topRowCells.get(0).getCellValue()==null||topRowCells.get(0).getCellValue().toString().trim().length()==0||!topRowCells.get(0).getCellValue().toString().trim().equals("登录号")) {
							state=true;
						}
						if(topRowCells.get(1).getCellValue()==null||topRowCells.get(1).getCellValue().toString().trim().length()==0||!topRowCells.get(1).getCellValue().toString().trim().equals("姓名")) {
							state=true;
						}
						if(state) {
							rmsg.append("您使用导入模板的表头不正确，请确认后重新导入！");
							return rmsg.toString();
						}
					}catch(Exception e) {
						rmsg.append("您使用导入模板的表头不正确，请确认后重新导入！");
						return rmsg.toString();
					}				
					//如果已经添加的预授权人数和本次预授权人数之和小于等于参学名额限报人数便可以添加，否则不能添加
					if(parNum+eRows.size()-1<=restrictPersonNum){//没超过
						Map<String,PreAuthorizationRegistrationValidCommond> map=new HashMap<String,PreAuthorizationRegistrationValidCommond>();
						List<String> loginIds=new ArrayList<String>();//所有的登陆ids
						//开始获取单元格的值
						for(int i=1;i<eRows.size();i++){
							ExcelRow eRow=eRows.get(i);
							try {
								PreAuthorizationRegistrationValidCommond cvommond=new PreAuthorizationRegistrationValidCommond();
								List<ExcelCell> eCells =eRow.getCellList();
								//第一列为登陆号
								if(eCells.get(0).getCellValue()==null||eCells.get(0).getCellValue().toString().trim().length()==0) {
									rmsg.append("第" + eRow.getRowNum() + "行 \"登陆号\" " + "列不能为空，请修改后重新导入。<br/>") ;	
								}
								if(!(eCells.get(0).getCellValue()==null||eCells.get(0).getCellValue().toString().trim().length()==0)) {
									//如果登录号是纯数字时传入后台为double类型，所以需要转化一下
									String sContentValue =eCells.get(0).getCellValue().toString();
									boolean bCheckResult = true;
									Double dCheckValue=0.0;
									try{   
										dCheckValue = Double.parseDouble(sContentValue); 
										if (dCheckValue instanceof Double == false){  
											bCheckResult = false;  
										}  
									}catch(NumberFormatException e){    
										bCheckResult = false;  
									}  
									if(bCheckResult){
										Integer loginId=dCheckValue.intValue();
										loginIds.add(loginId.toString());
										cvommond.setLoginId(loginId.toString());
										if(eCells.get(0).getCellValue()!=null&&loginId.toString().trim().length()>15) {
											rmsg.append("第" + eRow.getRowNum() + "行 \"登陆号\" " + "列输入字数超过了15字，请修改后重新导入。<br/>") ;	
										}
									}else{
										loginIds.add(eCells.get(0).getCellValue().toString());
										cvommond.setLoginId(eCells.get(0).getCellValue().toString());
										if(eCells.get(0).getCellValue()!=null&&eCells.get(0).getCellValue().toString().trim().length()>15) {
											rmsg.append("第" + eRow.getRowNum() + "行 \"登陆号\" " + "列输入字数超过了15字，请修改后重新导入。<br/>") ;	
										}
									}
								}
								//第二列为姓名
								if(eCells.get(1).getCellValue()==null||eCells.get(1).getCellValue().toString().trim().length()==0) {
									rmsg.append("第" + eRow.getRowNum() + "行 \"姓名\" " + "列不能为空，请修改后重新导入。<br/>") ;
								}
								if(eCells.get(1).getCellValue()!=null&&eCells.get(1).getCellValue().toString().trim().length()>10) {
									rmsg.append("第" + eRow.getRowNum() + "行 \"姓名\" " + "列输入字数超过了10字，请修改后重新导入。<br/>") ;
								}
								if(!(eCells.get(1).getCellValue()==null||eCells.get(1).getCellValue().toString().trim().length()==0)){
									cvommond.setUserName(eCells.get(1).getCellValue().toString());
								}
								//补全其他属性
								cvommond.setYear(a.get(Calendar.YEAR));
								SignupDept d=new SignupDept();
								d.setDepid(vCommond.getDeptId());
								cvommond.setDepartment(d);
								//调用dao层:根据部门id和登陆号查询此部门是否存在此用户
								List<UserInfoBean> users = preAuthorizationRegistrationDao.findBaseUser(cvommond.getLoginId(),vCommond.getDeptId());
								if(PropertyUtil.objectNotEmpty(users)&&users.size()>0){//存在此用户
									User user=new User();
									UserInfoBean userInfoBean=users.get(0);
									user.setUserId(userInfoBean.getUserId());
									cvommond.setUser(user);
								}else{//不存在此用户
									msg.append("第" + eRow.getRowNum() + "行用户不存在,请重新添加！<br/>");
								}
								list.add(cvommond);
								if(PropertyUtil.objectNotEmpty(cvommond)&&PropertyUtil.objectNotEmpty(cvommond.getLoginId())){
									map.put(cvommond.getLoginId(), cvommond);
								}
							}catch (Exception e){
								rmsg.append("第" + eRow.getRowNum() + "行数据不正确，请修改后重新导入。 <br/>");
							}
						}
						if(!rmsg.toString().equals("")){
							return rmsg.toString();
						}
						//判断本次预授权人员中是否有重复记录
						if(PropertyUtil.objectNotEmpty(map)&&map.size()>0){
							//获得所有登录号
							Set<String> loginIdss=map.keySet();
							if(loginIdss.size()!=loginIds.size()){
								return "本次预授权人员中存在重复记录，请修改后重新导入。";
							}
						}
						//查询本次预授权的人中是否存在当前年预授权的记录
						PreAuthorizationRegistrationQueryCommond  queryCommond=new PreAuthorizationRegistrationQueryCommond();
						queryCommond.setSearchLoginIds(loginIds);
						queryCommond.setSearchYear(a.get(Calendar.YEAR));
						queryCommond.setSearchDeptId(vCommond.getDeptId());
						List<?> lists=this.findAllList(queryCommond);
						if(PropertyUtil.objectNotEmpty(lists)&&lists.size()>0){//如果已经有人预授权给出提示
							msg.append("本次预授权人员中存在已经预授权的人员！");
						}				
					}else{//超过了给出提示
						msg.append("已超过此单位年度参学名额限报人数 ！");
					}
				}else{//没有参学名额给出提示
					msg.append("此单位本年没有分配参学名额，请分配以后再添加报名预授权！");
				}						
			}else{
				msg.append("您导入的数据为空，请确认后重新导入！");
			}
			if(!msg.toString().equals("")) {
				return msg.toString();
			}
			//执行添加
			if(list!=null&&list.size()>0) {
				for(int i=0;i<list.size();i++) {
					PreAuthorizationRegistrationValidCommond c=list.get(i);
					this.save(c);
				}
			}
			return "";
		}
	}
	
	@Override
	public List<PreAuhorzaionQueryBean> findPreAuthorZationRegistrationInfolist(
			PreAuthorizationRegistrationQueryCommond qCommond) throws Exception {
		return preAuthorizationRegistrationDao.findPreAuthorZationRegistrationInfolist(qCommond);
	}

	@Override
	public int updatePreAuthorZationRegistrationInfolist(
			PreAuthorizationRegistrationValidCommond vCommond) throws Exception {
		return preAuthorizationRegistrationDao.updatePreAuthorZationRegistrationInfolist(vCommond);
		
	}

	@Override
	public int deletePreAuthorZationRegistrationInfolist(
			PreAuthorizationRegistrationQueryCommond qCommond) throws Exception {
		return preAuthorizationRegistrationDao.deletePreAuthorZationRegistrationInfolist(qCommond);
	}

	@Override
	public PreAuhorzaionQueryBean prePreAuthorZationRegistrationInfo(
			PreAuthorizationRegistrationValidCommond vCommond) throws Exception {
		return preAuthorizationRegistrationDao.prePreAuthorZationRegistrationInfo(vCommond);
	}
	
	
	/**
	 * 查询某部门已报人数，和剩余人数
	 * @param String
	 * @return
	 * @throws Exception
	 * @author Max
	 * @date 2015-1-14
	 */
	@Override
	public PreSqSyUserBean findSignUNumByDepId(
			PreAuthorizationRegistrationQueryCommond vCommond) throws Exception {
		
		PreSqSyUserBean pb=new PreSqSyUserBean();
		ClassUserQueryCommond uqCommond=new ClassUserQueryCommond();
		
		//查询班级已报人数
		//uqCommond.setSearchClassID(vCommond.getSearchClassId());
		uqCommond.setSearchDepId(vCommond.getSearchDeptId());
		
		TrainingClassValidCommond co=trainingClassService.find(vCommond.getSearchClassId());
		String searchYear=co.getClassnameYear();//年份
		uqCommond.setSearchSignUpYear(searchYear);
		//查询班级信息
		//查询今年这个班级类型下这个部门的参学名额
		TrainingClass c=(TrainingClass)co.toEntity();
		String searchClassType="1";
		if(c.getClassType().getDataCode().equals("gfb")) {
			searchClassType="2";
		}else {
			searchClassType="1";
		}
		uqCommond.setSearchClassCategory(searchClassType);
		Long num1=classUserDao.getCountSelectedUserList(uqCommond);
		Integer num2=deptAssignedInfoDao.getNumByYearAndDept(vCommond.getSearchDeptId(), searchClassType, searchYear);
		
		//参学名额的数量
		pb.setSqAllUserNum(num2);//总名额
		pb.setSqUserNum(Integer.parseInt(num1.toString()));//已报多少人
		if(num2-Integer.parseInt(num1.toString())<0) {
			pb.setSyUserNum(0);//剩余多少人
		}else {
			pb.setSyUserNum(num2-Integer.parseInt(num1.toString()));//剩余多少人
		}
		//指定单位的数量
		ClassDeptQueryCommond classDeptQueryCommond=new ClassDeptQueryCommond();
		classDeptQueryCommond.setSearchClassId(vCommond.getSearchClassId());
		classDeptQueryCommond.setSearchDepId(vCommond.getSearchDeptId());
		//指定单位的分配人数
		List<ClassDeptValidCommond> classDeptList=(List<ClassDeptValidCommond>)classDeptService.findList(classDeptQueryCommond);
		InteriorUserQueryCommond queryCommond=new InteriorUserQueryCommond();
		queryCommond.setSearchClassId(vCommond.getSearchClassId());
		queryCommond.setSeachDepId(vCommond.getSearchDeptId());
		queryCommond.setSearchSigupYear(searchYear);
		//这个单位本班的报名人数
		List<DeptSignupBean> deptSignBenList=interiorUserService.getDeptSignupNum(queryCommond);
		
		if(classDeptList!=null&&classDeptList.size()>0) {
			pb.setClassSqAllUserNum(classDeptList.get(0).getLimitNum());
		}
		if(PropertyUtil.objectNotEmpty(deptSignBenList)&&deptSignBenList.size()>0){
			DeptSignupBean deptSignupBean=deptSignBenList.get(0);
			pb.setClassSqUserNum(deptSignupBean.getSignupNum().intValue());
		}
		pb.setClassSyUserNum(pb.getClassSqAllUserNum()-pb.getClassSqUserNum());
		return pb;
	}
	
}
